<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container>
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12" >
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="confirmCode">
              <a-input v-model="model.confirmCode" disabled placeholder="请输入单据编号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="包装班组" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="team">
              <j-search-select-tag v-model="model.team" :disabled="formDisabled"
              :dictOptions="teamDictOptions"
              placeholder="请选择包装班组" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <!-- 子表单区域 -->
          <a-tabs v-model="activeKey" @change="handleChangeTabs">
            <a-tab-pane tab=" " :key="refKeys[0]" :forceRender="true">
              <j-vxe-table
                keep-source  
                :ref="refKeys[0]"
                :loading="erpPackageFirstConfirmDetailTable.loading"
                :columns="erpPackageFirstConfirmDetailTable.columns"
                :dataSource="erpPackageFirstConfirmDetailTable.dataSource"
                :maxHeight="300"
                :disabled="formDisabled"
                :rowNumber="true"
                :rowSelection="false"
                :toolbar="false"/>
            </a-tab-pane>
          </a-tabs>
        <a-row style="margin-top: 15px">
          <a-col :span="24" >
            <a-form-model-item label="异常记录" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="abnormalRecord">
              <a-textarea v-model="model.abnormalRecord" :disabled="formDisabled" rows="4" placeholder="请输入异常记录" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24" >
            <a-form-model-item label="处置方案" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="disposalPlan">
              <a-textarea v-model="model.disposalPlan" :disabled="formDisabled" rows="4" placeholder="请输入处置方案" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getAction, putAction } from '@/api/manage'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'

  export default {
    name: 'ErpPackageFirstConfirmForm',
    mixins: [JVxeTableModelMixin],
    components: {
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{
        },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          confirmCode: [
              { required: true, message: '记录单号不能为空!'},
           ],
           team: [
              { required: true, message: '包装班组不能为空!'},
           ],
        },
        refKeys: ['erpPackageFirstConfirmDetail', ],
        tableKeys:['erpPackageFirstConfirmDetail', ],
        activeKey: 'erpPackageFirstConfirmDetail',
        // 包装现场首件检明细
        erpPackageFirstConfirmDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '计划单号',
              key: 'planCode',
              type: JVXETypes.normal,
              disabled:true,
              width:"200px",
              defaultValue:'',
            },
            {
              title: '订单编号',
              key: 'orderCode',
              type: JVXETypes.normal,
              disabled:true,
              width:"200px",
              defaultValue:'',
            },
            {
              title: '物料名称',
              key: 'materialName',
              type: JVXETypes.normal,
              disabled:true,
              width:"200px",
              defaultValue:'',
            },
            {
              title: '内袋',
              key: 'inBag',
              type: JVXETypes.checkbox,
              customValue: [1, 0],
              disabled: this.disabled,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '外袋',
              key: 'outBag',
              type: JVXETypes.checkbox,
              customValue: [1, 0],
              disabled: this.disabled,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '粉体白度',
              key: 'powderWhiteness',
              type: JVXETypes.checkbox,
              customValue: [1, 0],
              disabled: this.disabled,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '粉体颗粒',
              key: 'powderParticles',
              type: JVXETypes.checkbox,
              customValue: [1, 0],
              disabled: this.disabled,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '视比重',
              key: 'apparentGravity',
              type: JVXETypes.checkbox,
              customValue: [1, 0],
              disabled: this.disabled,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '非离子团',
              key: 'nonionicGroup',
              type: JVXETypes.checkbox,
              customValue: [1, 0],
              disabled: this.disabled,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '香精团',
              key: 'essenceGroup',
              type: JVXETypes.checkbox,
              customValue: [1, 0],
              disabled: this.disabled,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '香精',
              key: 'essence',
              type: JVXETypes.checkbox,
              customValue: [1, 0],
              disabled: this.disabled,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '点缀物',
              key: 'embellishments',
              type: JVXETypes.checkbox,
              customValue: [1, 0],
              disabled: this.disabled,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '钢印',
              key: 'steelStamp',
              type: JVXETypes.checkbox,
              customValue: [1, 0],
              disabled: this.disabled,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '合格证',
              key: 'certificateConformity',
              type: JVXETypes.checkbox,
              customValue: [1, 0],
              disabled: this.disabled,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '胶带',
              key: 'tape',
              type: JVXETypes.checkbox,
              customValue: [1, 0],
              disabled: this.disabled,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '计量称',
              key: 'measuringScale',
              type: JVXETypes.checkbox,
              customValue: [1, 0],
              disabled: this.disabled,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
          ]
        },
        url: {
          add: "/packagefirstconfirm/erpPackageFirstConfirm/add",
          edit: "/packagefirstconfirm/erpPackageFirstConfirm/edit",
          queryById: "/packagefirstconfirm/erpPackageFirstConfirm/queryById",
          erpPackageFirstConfirmDetail: {
            list: '/packagefirstconfirm/erpPackageFirstConfirm/queryErpPackageFirstConfirmDetailByMainId',
          },
        },
        // 班组字典
        teamDictOptions:[],
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      //新增功能的传值
      confirmationData: {
        type: Object,
        default: () => ({}),
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
      // 获取班组
      this.loadTeamDict();
    },
    methods: {
      addBefore(){
        this.erpPackageFirstConfirmDetailTable.dataSource=[]
        this.getSequenceNum()
        this.getPackageDetailList()
      },
      //获取确认记录单号
      getSequenceNum() {
        let url = '/sys/fillRule/executeRuleByCode/package_fist_code'
        putAction(url, {}).then((res) => {
          // 执行成功，获取返回的值，并赋到页面上
          if (res.success) {
            this.model = 
            {
              ...this.confirmationData,
              confirmCode: res.result
            }
          }
        })
      },
      //获取包材物料信息
      getPackageDetailList() {
        let url = '/packagefirstconfirm/erpPackageFirstConfirm/queryPackagePlanDetail'
        let params = {
          planId: this.confirmationData.planId,
          packshopCode: this.confirmationData.packshopCode,
        }
        getAction(url, params).then((res) => {
          if (res.success) {
            this.erpPackageFirstConfirmDetailTable.dataSource = res.result || res.result.records;
          }
        })
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.erpPackageFirstConfirmDetail.list, params, this.erpPackageFirstConfirmDetailTable)
        }
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
          return new Promise((resolve,reject)=>{
            Promise.all([
            ]).then(() => {
              resolve(allValues)
            }).catch(e => {
              if (e.error === VALIDATE_FAILED) {
                // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
              } else {
                console.error(e)
              }
            })
          })
      },
      // /** 整理成formData */
      // classifyIntoFormData(allValues) {
      //   let main = Object.assign(this.model, allValues.formValue)
      //   return {
      //     ...main, // 展开
      //     erpPackageFirstConfirmDetailList: allValues.tablesValue[0].tableData,
      //   }
      // },
      // 修改classifyIntoFormData方法 目的是为了删除自动生成的row_id字段
      classifyIntoFormData(allValues) {
        // 先获取原始表单数据
        const formData = {
          ...this.model,
          ...allValues.formValue,
          erpPackageFirstConfirmDetailList: allValues.tablesValue[0].tableData
        };
        // 处理子表数据：移除自动生成的临时ID
        if (formData.erpPackageFirstConfirmDetailList && formData.erpPackageFirstConfirmDetailList.length > 0) {
          formData.erpPackageFirstConfirmDetailList = formData.erpPackageFirstConfirmDetailList.map(item => {
            // 删除临时生成的id字段
            if (item.id && item.id.startsWith('row_')) {
              const { id, ...rest } = item;
              return rest;
            }
            return item;
          });
        }
        return formData;
      },
      validateError(msg){
        this.$message.error(msg)
      },
      // 加载班组
      loadTeamDict(){
        getAction(`/sys/sysDepart/querySuborderDepart`,{ orgCode: this.confirmationData.packshopCode }).then(res=>{
          if(res.success){
            this.teamDictOptions = res.result.map(item => ({value: item.orgCode, text: item.departName}))
          } else {
            this.teamDictOptions = []
          }
        })
      },
    }
  }
</script>

<style scoped>
</style>